## 图片集合转GIF
from PIL import Image
import os

def create_gif(input_folder, output_file, fps=10, resize_factor=1.0, quality=95):
    # 获取文件夹中所有的图片文件
    images = []
    for file_name in sorted(os.listdir(input_folder)):
        if file_name.endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
            img_path = os.path.join(input_folder, file_name)
            img = Image.open(img_path)
            
            # 调整图片大小
            if resize_factor != 1.0:
                width, height = img.size
                img = img.resize((int(width * resize_factor), int(height * resize_factor)))
            
            # 降低图片质量（通过设置JPEG质量）
            img = img.convert("RGB")
            img.save(f"temp_{file_name}", "JPEG", quality=quality)
            images.append(img)

    # 使用 PIL 的 save 方法创建 GIF
    images[0].save(output_file, save_all=True, append_images=images[1:201], optimize=True, duration=1000/fps, loop=0)

    # 删除临时图片
    for img in images:
        if isinstance(img, Image.Image):
            img.close()

    print(f"GIF has been saved to {output_file}")

if __name__ == "__main__":
    input_folder = r"D:\研究生\科研相关\比赛\多维度无人化海上巡逻系统\国赛报名-智慧城市\演示图片\流体力学仿真\vocity"  # 输入图片文件夹路径
    output_file = r"D:\研究生\科研相关\比赛\多维度无人化海上巡逻系统\国赛报名-智慧城市\演示图片\流体力学仿真\gif\gif_vocity.gif"  # 输入输出GIF路径
    fps = 8  # 输入每秒帧数
    resize_factor = 0.4  # 输入尺寸缩放比例
    quality = 20  # 输入GIF的压缩质量

    create_gif(input_folder, output_file, fps, resize_factor, quality)
